import axios from "axios";
import { Message } from "element-ui";
import STATUS from "../enum/STATUS.js";

// const aNotLoginPage = ["/login"];
// const loginPage = "/login";

// axios#request(config)
// axios#get(url[, config])
// axios#delete(url[, config])
// axios#head(url[, config])
// axios#options(url[, config])
// axios#post(url[, data[, config]])
// axios#put(url[, data[, config]])
// axios#patch(url[, data[, config]])
// axios.defaults.timeout = 5000;
axios.interceptors.request.use(
  function(resp) {
    // let isLogin = resp.headers.isLogin === undefined ? true : resp.headers.isLogin;
    let isLogin = resp.headers.isLogin !== false;
    let hasCorporationId = resp.headers.hasCorporationId !== false;
    let localSid = localStorage.getItem("sid");
    let sid = localSid ? JSON.parse(localSid) : {};
    // let currentCorporationId = localStorage.getItem("currentCorporationId") || '';
    // console.log('localStorage', localStorage.getItem("currentCorporation"))
    // 渠道用户不存在公司
    let localCurrentCorporation = localStorage.getItem("currentCorporation");
    let currentCorporation =
      localCurrentCorporation && localCurrentCorporation != "undefined"
        ? JSON.parse(localCurrentCorporation)
        : {};

    let currentCorporationId = currentCorporation.id;
    // 有公司，带上公司
    if (currentCorporationId && hasCorporationId) {
      // get方式，放在params，否则放在data
      if (resp.method == "get") {
        resp.params = resp.params || {};
        resp.params.tenantId = currentCorporationId;
      } else {
        resp.data = resp.data || {};
        resp.data.tenantId = currentCorporationId;
      }
    }
    // 没有登陆-跳到登陆页面
    if (isLogin && !sid.access_token) {
      location.replace(localStorage.getItem("logoutURL"));
      return;
    }
    if (isLogin) {
      resp.headers["Authorization"] = "bearer " + sid.access_token;
      delete resp.headers.isLogin;
    }
    return resp;
  },
  function(error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  function(resp) {
    let respData = resp.data || {};
    let errLv = respData.errLv || 3; // 1是登录提示、2是token失效、3是token过期、大于3是其他

    switch (respData.code) {
      case STATUS.identity_error[0]: // 没登陆
        if (errLv >= 1) {
          Message({
            message: respData.msg || STATUS.identity_error[1],
            onClose() {
              localStorage.clear();
              location.replace("/admin");
            }
          });

          return false;
        } else {
          return resp;
        }

      case STATUS.token_error[0]: // token过期了
        if (errLv >= 2) {
          Message({
            message: respData.msg || STATUS.token_error[1],
            onClose() {
              localStorage.clear();
              location.replace("/admin");
            }
          });

          return false;
        } else {
          return resp;
        }
      // 过期
      case STATUS.token_overdue[0]:
        if (errLv >= 3) {
          var config = resp.config;
          let localSid = localStorage.getItem("sid");
          let sid = localSid ? JSON.parse(localSid) : {};
          axios
            .post(config.refreshTokenUrl, {
              data: {
                grant_type: "refresh_token",
                refresh_token: sid.refresh_token
              },
              header: {
                "content-type": "application/x-www-form-urlencoded"
              }
            })
            .then(
              tokenResp => {
                let tokenRespData = tokenResp.data || {};
                if (tokenRespData.code === STATUS.success[0]) {
                  localStorage.setItem(
                    "sid",
                    JSON.stringify(tokenRespData.data)
                  );
                  config.headers["Authorization"] =
                    "bearer " + tokenRespData.access_token;
                  return axios(config);
                } else {
                  Message.error("刷新token失败");
                  return Promise.resolve(tokenResp);
                }
              },
              error => {
                return Promise.reject(error);
              }
            );
          return false;
        } else {
          return resp;
        }
      default:
        return resp;
    }

    // 对响应数据做点什么
  },
  function(error) {
    Message("服务器或网络出现问题");
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
export default axios;
